package io.github.uicdb.badskill.clent;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.network.chat.Component;
import net.minecraft.util.Mth;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.glfw.GLFW;

public abstract class AbstractScrollPanel extends AbstractWidget {
    protected float relativeX, relativeY;
    protected float scale=1;
    protected final double scaleMin,scaleMax;
    protected boolean isScrolled=false;
    public AbstractScrollPanel(int pX, int pY, int pWidth, int pHeight, double scaleMin, double scaleMax) {
        super(pX, pY, pWidth, pHeight, Component.empty());
        this.scaleMin = scaleMin;
        this.scaleMax = scaleMax;
    }
    public void scrollToCenter(){
        relativeX =-(getWidth()/2f) ;
        relativeY = -(getHeight()/2f);
    }
    protected float getHitX(float px) {
        return (px - relativeX +getX())*scale ;
    }

    protected float getHitY(float py) {
        return (py - relativeY +getY())*scale ;
    }


    protected abstract void renderToolTip(GuiGraphics pPoseStack, int pMouseX, int pMouseY);

    protected abstract void renderBg(GuiGraphics pPoseStack, Minecraft instance, int pMouseX, int pMouseY);

    @Override
    protected void updateWidgetNarration(@NotNull NarrationElementOutput elementOutput) {

    }
    @Override
    public boolean mouseClicked(double pMouseX, double pMouseY, int pButton) {
        if(!isScrolled&isValidClickButton(pButton))
             onPanelClick(pMouseX, pMouseY, pButton);
        return isMouseOver(pMouseX,pMouseY);
    }
    protected void onPanelClick(double pMouseX, double pMouseY, int pButton){
    };

    @Override
    public boolean mouseDragged(double pMouseX, double pMouseY, int pButton, double pDragX, double pDragY) {
        if(isMouseOver(pMouseX,pMouseY)&isValidClickButton(pButton)){
            relativeX -=pDragX;
            relativeY -=pDragY;
            isScrolled=true;
            return true;
        }
        return false;
    }

    @Override
    protected boolean isValidClickButton(int button) {
        return button== GLFW.GLFW_MOUSE_BUTTON_LEFT;
    }

    @Override
    public boolean mouseReleased(double pMouseX, double pMouseY, int pButton) {
        if(isScrolled) {
            isScrolled = false;
            return true;
        }
        return false;
    }

    @Override
    public boolean mouseScrolled(double pMouseX, double pMouseY, double pDelta) {
        if(isMouseOver(pMouseX,pMouseY)){
            if(pDelta>0) {
                scale = (float) Mth.clamp(scale+0.1f,scaleMin,scaleMax);
            }else if(pDelta<0){
                scale = (float) Mth.clamp(scale-0.1f,scaleMin,scaleMax);
            }
            return true;
        }
        return false;
    }
}
